package com.tfb.web.controller;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpSession;

public class SessionMgr {

    private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(SessionMgr.class);

    protected final static Map<String, HttpSession> apiSessionMap = Collections.synchronizedMap(new HashMap<String, HttpSession>());

    public static HttpSession getApiSession(String apiKey) {
        return apiSessionMap.get(apiKey);
    }

    public static void removeApiSession(String apiKey) {
        apiSessionMap.remove(apiKey);
    }

    public static void putApiSession(String apiKey, HttpSession httpSession) {
        apiSessionMap.put(apiKey, httpSession);

    }

    public static void removeApiSession(HttpSession httpSession) {
        if (log.isDebugEnabled()) {
            log.debug("Removing httpSession session...");
        }

        synchronized (apiSessionMap) {
            Iterator<?> it = apiSessionMap.values().iterator();
            while (it.hasNext()) {
                HttpSession theSession = (HttpSession) it.next();
                if (theSession == httpSession) {
                    it.remove();
                    break;
                }
            }
        }
    }
}
